package com.naxiang.zhaohang.naxiangvidoplay;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.baidu.cloud.media.player.IMediaPlayer;
import com.bumptech.glide.Glide;
import com.naxiang.zhaohang.utils.ItemBeen;
import com.naxiang.zhaohang.utils.NaXiangAdapter;
import com.naxiang.zhaohang.widget.BDCloudVideoView;
import com.naxiang.zhaohang.widget.BDCloudVideoView.PlayerState;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者: 赵航
 * 创建时间: 2018/7/4 20:47
 * 描述:
 */
public class NaXiangVidoPlay extends UZModule implements IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener, BDCloudVideoView.OnPlayerStateListener, IMediaPlayer.OnBufferingUpdateListener {

    private RelativeLayout mRela;
    private BDCloudVideoView mVV = null;
    private String mUri;
    private boolean isFull     = false;
    private boolean mFllScreen = false;
    private boolean mIsStoped  = false;
    private int                   mMaxProbeTime;
    private SimpleMediaController mMediaController;
    private UZModuleContext       mModuleContext;
    private int                   mMLift;
    private int                   mMTop;
    private int                   mMHight;
    private int                   mMWidth;
    private boolean               mMFixed;
    private String                mMIndexName;
    private boolean               mMoved;
    private String                mBigName;
    private boolean isMusic   = false;
    private boolean fullImage = false;

    private String  mImageUri  = "";
    //标记侧面是否滑出来
    private boolean mCloseOpen = false;
    private NaXiangAdapter mAdapter;
    private ObjectAnimator mAnimtion;
    private JSONArray      mVidoeUriList;
    private JSONArray      mImageUriList;
    private List<ItemBeen> itemBeens = new ArrayList<>();
    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    mHandler.removeCallbacksAndMessages(null);
                    break;
                case 2:
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();
                    if (currentPosition > 0 && duration > 0) {
                        long pos = 10000L * currentPosition / duration;
                        mMediaController.seatProgress((int) pos);
                        mMediaController.getSeekBar().setEnabled(true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mMediaController.getReadTime().setText(formatMilliSecond(mVV.getCurrentPosition()));
                                mMediaController.getAllTime().setText(formatMilliSecond(mVV.getDuration()));
                            }
                        });

                    } else {
                        mMediaController.getSeekBar().setEnabled(false);


                    }
                    break;
            }
        }
    };


    public NaXiangVidoPlay(UZWebView webView) {
        super(webView);
    }

    //打开播放器
    public void jsmethod_openVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;

        //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        }


        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = false;
        mMLift = moduleContext.optInt("lift", 0);
        mMTop = moduleContext.optInt("top", 0);
        mMHight = moduleContext.optInt("hight", 100);
        mMWidth = moduleContext.optInt("width", 100);
        mMFixed = moduleContext.optBoolean("fixed", false);
        mFllScreen = moduleContext.optBoolean("fullScreen", true);
        mMIndexName = moduleContext.optString("indexName", "");
        mImageUri = moduleContext.optString("imageuri", "");

        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");

        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());
            mMediaController.getImageView().setVisibility(View.GONE);
            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            mMediaController.getImageView().setVisibility(View.GONE);
            mRela.setBackgroundColor(Color.BLACK);
            removeViewFromCurWindow(mRela);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mMWidth, mMHight);
        params.setMargins(mMLift, mMTop, 0, 0);
        insertViewToCurWindow(mRela, params, mMIndexName, mMFixed);
        initViodView();
    }

    //打开全屏了
    public void jsmethod_openFullVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;

              //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        }


        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = true;
        int mLift = moduleContext.optInt("lift", 0);
        int mTop = moduleContext.optInt("top", 0);
        int mHight = moduleContext.optInt("hight", -1);
        int mWidth = moduleContext.optInt("width", -1);
        mMoved = moduleContext.optBoolean("fixed", false);
        mBigName = moduleContext.optString("indexName", "");
        mFllScreen = moduleContext.optBoolean("fullScreen", false);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");
        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mImageUri = moduleContext.optString("imageuri", "");
        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());

            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            removeViewFromCurWindow(mRela);
            mRela.setBackgroundColor(Color.BLACK);
            mMediaController.getImageView().setVisibility(View.VISIBLE);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mWidth, mHight);
        params.setMargins(mLift, mTop, 0, 0);
        //main
        insertViewToCurWindow(mRela, params, mBigName, mMoved);
        initViodView();


    }

    //点击暂停
    public void jsmethod_openPause(UZModuleContext moduleContext) {
        mVV.pause();
    }

    //点击开始
    public void jsmethod_openSatrt(UZModuleContext moduleContext) {

        if (!mVV.isPlaying()) {
            if (mIsStoped) {
                initViodView();
                mIsStoped = false;
            } else {
                mVV.start();
            }
        }
    }

    //点击停止
    public void jsmethod_openStop(UZModuleContext moduleContext) {
        mIsStoped = true;

        if (mVV.isPlaying()) {
            mVV.stopPlayback();
        }
    }

    //点击播放切换播放目录
    public void jsmethod_openNextPlay(UZModuleContext moduleContext) {

        mUri = moduleContext.optString("uri", "rtmp://live.hkstv.hk.lxdns.com/live/hks");

        boolean isPaly = moduleContext.optBoolean("isPlay", true);
        mVV.setVideoPath(mUri);
        mMediaController.getSeekBar().setProgress(0);
        if (isPaly) {
            mVV.start();

        }
    }

    //设置音量
    public void jsmethod_openVolumeSetting(UZModuleContext moduleContext) {

        double mVolume = moduleContext.optDouble("volume", 1.0);
        float nVolume = (float) mVolume;
        //设置声音
        mVV.setVolume(nVolume, nVolume);
        mVV.start();
    }


    //设置是否循环
    public void jsmethod_openLooper(UZModuleContext moduleContext) {

        boolean mLooper = moduleContext.optBoolean("looper", false);
        mVV.setLooping(mLooper);
        mVV.start();
    }

    //跳转到指定位置
    public void jsmethod_openSkipPostion(UZModuleContext moduleContext) {

        int mPosition = moduleContext.optInt("position", 1000);
        double mSpeed = moduleContext.optDouble("speed", 1.0);
        int mMaxSize = moduleContext.optInt("maxsizeinbytes", 1024);
        int mMaxProbeSize = moduleContext.optInt("maxprobesize", 1024);

        float speed = (float) mSpeed;
        mVV.seekTo(mPosition);
        mVV.setSpeed(speed);
        mVV.setMaxCacheSizeInBytes(mMaxSize);
        mVV.setMaxProbeSize(mMaxProbeSize);
        mVV.start();

    }

    //移除视频播放器
    public void jsmethod_removeVido(UZModuleContext moduleContext) {

        if (mRela != null) {
            mVV.stopPlayback();
            removeViewFromCurWindow(mRela);
        }


    }

    //是否显示进度条
    public void jsmethod_showProgress(UZModuleContext moduleContext) {
        boolean isShown = moduleContext.optBoolean("isShown", false);
        if (!isShown) {
            if (mRela != null) {
                mRela.removeView(mMediaController);
            }
        }
    }


    private void initViodView() {
        //这里判断是横竖屏
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mMediaController.getFullSecream().setSelected(false);
            mMediaController.getImageView().setVisibility(View.VISIBLE);
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);

        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mMediaController.getFullSecream().setSelected(true);
            mMediaController.getImageView().setVisibility(View.INVISIBLE);
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);
            mMediaController.getListView().setVisibility(View.INVISIBLE);
            if (mAnimtion != null) {
                mAnimtion.start();
            }
        }
        //视频比例和屏幕比例不一致的话，默认不能全屏问题
        if (mFllScreen) {
            //视频占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
        } else {
            //            视频不占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        }
        //TODO:保证不息屏
        getContext().getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //TODO:设置显示的大小
        //        api.winWidth
        //        api.winHeight

        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-1, -1);
        //        rllp.addRule(RelativeLayout.CENTER_IN_PARENT);
        mRela.removeAllViews();
        mRela.addView(mVV, rllp);
        mRela.addView(mMediaController);
        mVV.setVideoPath(mUri);
        mVV.setMaxProbeTime(mMaxProbeTime); // 设置首次缓冲的最大时长
        mVV.setTimeoutInUs(1000000);

        //播放器准备好的监听
        //        mVV.setOnPreparedListener(this);
        //        mVV.setOnCompletionListener(this);

        //播放错误监听
        mVV.setOnErrorListener(this);
        //播放信息监听
        mVV.setOnInfoListener(this);

        //该方法主要用于进度条的监听
        mVV.setOnBufferingUpdateListener(this);
        //播放状态监听，主要用于进度条的监听
        mVV.setOnPlayerStateListener(this);

        //开始播放
        if (!mVV.isPlaying() && fullImage) {
            mVV.start();
        }


        //全屏返回按钮的点击事件
        mMediaController.getImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先移除布局
                removeViewFromCurWindow(mRela);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mMWidth, mMHight);
                params.setMargins(mMLift, mMTop, 0, 0);

                if (mMIndexName != null) {
                    insertViewToCurWindow(mRela, params, mMIndexName, mMFixed);
                } else {
                    insertViewToCurWindow(mRela, params, mBigName, mMFixed);
                }
                //在记录当前状态
                isFull = !isFull;
                initPlay();

            }
        });

        //加载图片
        if (!fullImage) {
            Glide.with(getContext())
                    .load(mImageUri)
                    .error(R.drawable.ic_play)
                    .into(mMediaController.getViodPicrure());
        }


        //点击开始和暂停按钮
        mMediaController.getImageStart().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mVV.isPlaying()) {
                    mVV.pause();
                } else {
                    mVV.start();
                }
                if (!fullImage) {
                    Glide.with(getContext())
                            .load("")
                            .error(R.drawable.writback)
                            .into(mMediaController.getViodPicrure());
                    mVV.start();
                }
                fullImage = true;
            }
        });


        //TODO:设置进度条的点击事件
        mMediaController.getSeekBar().setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.getReadTime().setText(formatMilliSecond(progress));
                    }
                });
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (mVV.getDuration() > 0) {
                    int i = (mVV.getDuration() * progress) / 10000;
                    mVV.seekTo(i);
                    seekBar.setEnabled(true);
                } else {
                    seekBar.setEnabled(false);
                }
            }
        });


        //点击进行横竖屏切换
        mMediaController.getFullSecream().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isFull) {
                    //先移除布局
                    removeViewFromCurWindow(mRela);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mMWidth, mMHight);
                    params.setMargins(mMLift, mMTop, 0, 0);

                    //再添加布局

                    //再添加布局
                    if (mMIndexName != null) {
                        insertViewToCurWindow(mRela, params, mMIndexName, mMFixed);
                    } else {
                        insertViewToCurWindow(mRela, params, mBigName, mMoved);
                    }
                    mMediaController.getFullSecream().setSelected(false);
                    isFull = !isFull;
                    //再开始播放

                    //                    initViodView();
                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    initPlay();
                } else {
                    //先移除布局
                    removeViewFromCurWindow(mRela);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
                    params.setMargins(0, 0, 0, 0);

                    //再添加布局
                    if (mBigName != null) {
                        insertViewToCurWindow(mRela, params, mBigName, mMoved);
                    } else {
                        insertViewToCurWindow(mRela, params, mMIndexName, mMFixed);
                    }
                    mMediaController.getFullSecream().setSelected(true);
                    isFull = !isFull;
                    //再开始播放
                    //                    initViodView();

                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    initPlay();
                }

            }
        });

        //点击静音
        mMediaController.getMusicClose().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMusic = !isMusic;
                if (isMusic) {
                    mMediaController.getMusicClose().setSelected(true);
                    mVV.setVolume(0, 0);
                    mVV.start();
                } else {
                    mMediaController.getMusicClose().setSelected(false);
                    mVV.setVolume(1, 1);
                    mVV.start();
                }

            }
        });


        //设置侧滑点击事件
        //侧面划入滑出效果
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("TranslationX", 0f, -250f);
        PropertyValuesHolder animatorw = PropertyValuesHolder.ofFloat("TranslationX", -250f, 0.0f);
        mAnimtion = ObjectAnimator.ofPropertyValuesHolder(mMediaController.getSliedBar(), animator, animatorw).setDuration(0);
        mAnimtion.start();
        mMediaController.getSliedBar().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCloseOpen) {
                    mAnimtion.start();
                    mMediaController.setListVisible(false,itemBeens);
                } else {
                    mAnimtion.reverse();
                    mMediaController.setListVisible(true,itemBeens);
                }
                mCloseOpen = !mCloseOpen;
            }
        });


        //设置ListVIew的条目点击事件
        mMediaController.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAnimtion.start();
                mMediaController.getListView().setVisibility(View.INVISIBLE);
                mVV.setVideoPath(itemBeens.get(position).getVidoUri());
                if (!fullImage) {
                    Glide.with(getContext())
                            .load("")
                            .error(R.drawable.writback)
                            .into(mMediaController.getViodPicrure());
                }
                fullImage = true;
                mVV.start();
            }
        });
    }

    private void initPlay() {
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mMediaController.getFullSecream().setSelected(false);
            mMediaController.getImageView().setVisibility(View.VISIBLE);
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);
        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mMediaController.getFullSecream().setSelected(true);
            mMediaController.getImageView().setVisibility(View.INVISIBLE);
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);
            mMediaController.getListView().setVisibility(View.INVISIBLE);
            if (mAnimtion != null) {
                mAnimtion.start();
            }
        }
    }


    @Override
    public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
        return false;
    }


    @Override
    public void onPlayerStateChanged(PlayerState nowState) {

        System.out.println("播放状态监听");
        PlayerState state = mVV.getCurrentPlayerState();

        if (state == PlayerState.STATE_IDLE || state == PlayerState.STATE_ERROR) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();
                    mMediaController.getReadTime().setText(formatMilliSecond(currentPosition));
                    mMediaController.getAllTime().setText(formatMilliSecond(duration));
                }
            });

            //播放监听
        }else if (state == PlayerState.STATE_PLAYING){

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);

            //暂停监听
        }else if (state == PlayerState.STATE_PAUSED){
            mHandler.sendEmptyMessage(1);
        }else if (state == PlayerState.STATE_PREPARED) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);

        }



    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int percent) {
        if (mMediaController != null && mVV != null) {
            final long currentPosition = mVV.getCurrentPosition();
            long duration = mVV.getDuration();
            //TODO:设置更细化的进度

            if (currentPosition > 0 && duration > 0) {
                long pos = 10000L * currentPosition / duration;
                mMediaController.seatProgress((int) pos);
                mMediaController.getSeekBar().setEnabled(true);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.getReadTime().setText(formatMilliSecond(mVV.getCurrentPosition()));
                        mMediaController.getAllTime().setText(formatMilliSecond(mVV.getDuration()));
                    }
                });

            } else {
                mMediaController.getSeekBar().setEnabled(false);


            }
        }


        JSONObject object = new JSONObject();
        try {
            object.put("currentposition", iMediaPlayer.getCurrentPosition());
            object.put("duration", iMediaPlayer.getDuration());
            object.put("mediainfo", iMediaPlayer.getMediaInfo());

            //设置为false为不间断的想后台发送数据
            mModuleContext.success(object, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private String formatMilliSecond(int milliSecond) {
        int seconds = milliSecond / 1000;
        int hh = seconds / 3600;
        int mm = seconds % 3600 / 60;
        int ss = seconds % 60;
        String strTemp = null;
        if (0 != hh) {
            strTemp = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            strTemp = String.format("%02d:%02d", mm, ss);
        }
        return strTemp;
    }
}